package persistencia;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.util.LinkedList;
import java.util.List;

import modeloDatos.Pique;

public class DAOPicado {
	
	private Connection conn;

	public DAOPicado() {
		
	}
	
	public void finalize(){
        ConnectionManager.getInstance().checkIn(conn);
    }
	
	public Boolean insertarPique(String usuario, String tipo, String motivo){
		conn = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
		Date fecha = new Date(System.currentTimeMillis());
		Time hora = new Time(System.currentTimeMillis());
		String sql = "INSERT INTO piques (usuario,fecha,hora,timemillis,tipo,motivo) VALUES (?,?,?,?,?,?)";
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, usuario);
			stmt.setDate(2, fecha);
			stmt.setTime(3,hora);
			stmt.setInt(4, (int)System.currentTimeMillis());
			stmt.setString(5, tipo);
			stmt.setString(6, motivo);
			stmt.executeUpdate();
		} catch (SQLException ex) {
			System.out.println("Message: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			finalize();
			try {
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException ex) {
			}
		}
		return true;
	}
	
	public List<Pique> recuperarPiques(String usuario){
		conn = ConnectionManager.getInstance().checkOut();
		PreparedStatement stmt = null;
		String sql = "SELECT * FROM piques WHERE usuario=?";
        ResultSet result = null;
        List<Pique> listaP = new LinkedList<Pique>();
		try {
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, usuario);
			result = stmt.executeQuery();
			while (result.next()) {
				Pique p = new Pique();
				p.fecha=result.getDate("fecha");
				p.hora=result.getTime("hora");
				p.timemillis=result.getInt("timemillis");
				p.tipo=result.getString("tipo");
				p.motivo=result.getString("motivo");
				listaP.add(p);
			}
		} catch (SQLException ex) {
			System.out.println("Message: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("ErrorCode: " + ex.getErrorCode());
		} finally {
			finalize();
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException ex) {
			}
		}
		return listaP;
	}
}
